﻿using System;
using System.Collections.Generic;
using System.Text;
/*
 Reference implementations of simple validation classes to suggest idioms
 to use in custom implemenations (if that is not too grand, which I think perhaps it is).
 All validators should inherit from the BaseValidater as this implements the validater 
 chaining mechanism and includes a string property for the last error.
*/
namespace SimpleEntry
{
	/// <summary>
	/// Prevent empty input.
	/// The object gets tested for null, being of type DbNull or having a zero-length 
	/// string representation. 
	/// </summary>
	public class NonEmptyValidater : BaseValidater
	{
		protected override bool InternalValidate(object o, out string errorMessage)
		{
			errorMessage = "";
			if (o != null)
				if (o.GetType() != typeof(System.DBNull))
					if (o.ToString().Length > 0)
						return true;
			errorMessage = "Input cannot be empty. Please supply a value";
			return false;
		}
	}
	/// <summary>
	/// Validate that text entry is within a certain range of characters.
	/// You can probably do this via the winforms text control, but it's a
	/// </summary>
	public class TextRangeValidater : BaseValidater
	{
		public TextRangeValidater(int minLength, int maxLength)
		{
			this.m_Min = minLength;
			this.m_Max = maxLength;
		}

		protected override bool InternalValidate(object o, out string errorMessage)
		{
			errorMessage = "";
			if (IsEmpty(o)) return true; // allow empty

			int l = o.ToString().Length;
			if (l < m_Min || l > m_Max)
			{
				errorMessage = String.Format("input length should be between {0} and {1} characters", m_Min, m_Max);
				return false;
			}
			return true;
		}
		int m_Min;
		int m_Max;
	}

	public class RangeValidater<T> : BaseValidater where T : IComparable
	{
		public RangeValidater(T minLength, T maxLength)
		{
			this.m_Min = minLength;
			this.m_Max = maxLength;
		}

		protected override bool InternalValidate(object o, out string errorMessage)
		{
			errorMessage = "";
			if (IsEmpty(o)) return true; // allow empty

			T x = (T)o;
			if (x.CompareTo(this.m_Min) == -1 || x.CompareTo(this.m_Max) == 1)
			{
				errorMessage = String.Format("input should be between {0} and {1}.", m_Min, m_Max);
				return false;
			}
			return true;
		}
		T m_Min;
		T m_Max;
	}
	
}
